<template>
  <div class="my-plan-container">
    <div class="header-row">
      <h2>我的行程</h2>
      <el-button type="primary" @click="goHome" class="home-btn">返回首页</el-button>
    </div>
    <!-- 行程列表 -->
    <div v-loading="loading">
      <el-table :data="plans" style="width: 100%" border>
        <el-table-column prop="detail_id" label="行程id" width="80" align="center"/>
        <el-table-column prop="day_number" label="天数" width="80" align="center"/>
        <el-table-column label="日期" width="200">
          <template #default="{row}">
            {{ formatDate(row.start_time) }} - {{ formatDate(row.end_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="budget_range" label="预算" width="120"/>
        <el-table-column prop="budget_allocation" label="预算分配" width="120"/>
        <el-table-column prop="departure" label="出发地" width="80"/>
        <el-table-column prop="destination" label="目的地" width="80"/>
        <el-table-column label="当日活动">
          <template #default="{row}">
            <div class="activities">
              <div v-if="row.morning_activity" class="activity-item">
                <span class="time-tag morning">上午</span>{{ row.morning_activity }}
              </div>
              <div v-if="row.afternoon_activity" class="activity-item">
                <span class="time-tag afternoon">下午</span>{{ row.afternoon_activity }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="hotel_recommendation" label="酒店推荐" width="180"/>
        <el-table-column label="操作" width="120" align="center">
          <template #default="{row}">
            <el-button
                type="danger"
                size="small"
                @click="handleDelete(row.detail_id)"
                icon="Delete"
            />
          </template>
        </el-table-column>
      </el-table>



      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
            background
            layout="prev, pager, next, sizes"
            :current-page="pagination.current"
            :page-size="pagination.size"
            :page-sizes="[5, 10, 20]"
            :total="pagination.total"
            @current-change="handlePageChange"
            @size-change="handleSizeChange"
        />
      </div>
    </div>

    <!-- 错误提示 -->
    <el-alert
        v-if="errorMessage"
        :title="errorMessage"
        type="error"
        show-icon
        class="error-alert"
        @close="errorMessage = ''"
    />
  </div>

</template>

<script>
import axios from 'axios'
import dayjs from 'dayjs'
import {useRouter} from "vue-router";


export default {
  name: 'MyPlan',
  setup() {
    const router = useRouter()

    // 新增首页跳转方法
    const goHome = () => {
      router.push('/')
    }

    return {
      goHome
    }
  },
  data() {
    return {
      loading: false,
      errorMessage: '',
      plans: [],
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      // 从Vuex或本地存储获取当前用户ID
      // userId: localStorage.getItem('userId') || 2 // 示例默认值
      userId: localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')).user_id : null
    }
  },
  mounted() {
    this.fetchPlans()
  },
  methods: {
    async handleDelete(detailId) {
      try {
        await this.$confirm('此操作将永久删除该行程，是否继续？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        const response = await axios.delete(`${BASE_URL}/itinerary-details/${detailId}`)

        if (response.data.state === 200) {
          this.$message.success('删除成功')
          // 重新获取数据
          await this.fetchPlans()
          // 处理可能存在的分页边界情况
          if (this.plans.length === 0 && this.pagination.current > 1) {
            this.pagination.current--
            await this.fetchPlans()
          }
        } else {
          this.$message.error(response.data.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败，请稍后重试')
          console.error('删除行程失败:', error)
        }
      }
    },

    async fetchPlans() {
      // 新增登录状态检查
      if (!this.userId) {
        this.errorMessage = '请先登录以查看行程'
        this.$router.push('/login')  // 跳转到登录页
        return
      }
      this.loading = true
      try {
        const response = await axios.get(BASE_URL+'/itinerary-details/user/page', {
          params: {
            userId: this.userId,
            page: this.pagination.current,
            pageSize: this.pagination.size
          }
        })
        console.log('完整响应结构:', response)  // 调试日志
        // 添加响应数据检查
        if (!response?.data?.data) {
          console.error('异常响应结构:', response)
          this.errorMessage = '服务器返回数据格式异常'
          return
        }
        if (response.data.state === 200) {
          const responseData = response.data.data || {}; // 添加空对象保护
          const list = responseData.list || [];
          const total = responseData.total || 0;
          this.plans = list;
          this.pagination.total = total;
        } else {
          this.errorMessage = response.data.message || '获取行程数据失败'
        }
      } catch (error) {
        this.errorMessage = '请求失败，请检查网络连接'
        console.error('获取行程失败:', error)
      } finally {
        this.loading = false
      }
    },

    formatDate(dateStr) {
      return dayjs(dateStr).format('YYYY-MM-DD HH:mm')
    },

    handlePageChange(currentPage) {
      this.pagination.current = currentPage
      this.fetchPlans()
    },

    handleSizeChange(pageSize) {
      this.pagination.size = pageSize
      this.pagination.current = 1
      this.fetchPlans()
    }
  }
}
</script>

<style scoped>
.header-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
      padding: 0 10px;
}

.home-btn {
  background-color: #409eff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.home-btn:hover {
  background-color: #66b1ff;
  box-shadow: 0 2px 6px rgba(64, 158, 255, 0.3);
}

.my-plan-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.error-alert {
  margin-top: 20px;
}

.activities {
  padding: 8px 0;
}

.activity-item {
  margin: 6px 0;
  display: flex;
  align-items: center;
}

.time-tag {
  display: inline-block;
  padding: 2px 6px;
  border-radius: 4px;
  margin-right: 8px;
  font-size: 12px;
  color: white;
}

.morning {
  background-color: #67C23A;
}

.afternoon {
  background-color: #E6A23C;
}
</style>




<!--<template>-->
<!--  <div class="my-plan-container">-->
<!--    <el-card class="plan-card">-->
<!--      <template v-slot:header>-->
<!--        <div class="card-header">-->
<!--          <h2>我的行程</h2>-->
<!--          <el-select-->
<!--              v-model="filterStatus"-->
<!--              placeholder="筛选状态"-->
<!--              class="filter-select"-->
<!--              @change="fetchPlans"-->
<!--          >-->
<!--            <el-option-->
<!--                v-for="item in statusOptions"-->
<!--                :key="item.value"-->
<!--                :label="item.label"-->
<!--                :value="item.value"-->
<!--            />-->
<!--          </el-select>-->
<!--        </div>-->
<!--      </template>-->

<!--      <el-table-->
<!--          :data="plans"-->
<!--          style="width: 100%"-->
<!--          v-loading="loading"-->
<!--      >-->
<!--        <el-table-column prop="detail_id" label="ID" width="80" />-->
<!--        <el-table-column label="行程概览">-->
<!--          <template  #default="{row}">-->
<!--            <div class="plan-overview">-->
<!--              <div class="destination">-->
<!--                <el-icon><Location /></el-icon>-->
<!--                {{ row.destination }}（{{ row.duration_days }}天）-->
<!--              </div>-->
<!--              <div class="budget">-->
<!--                <el-icon><Coin /></el-icon>-->
<!--                预算：{{ row.budget_range }}-->
<!--              </div>-->
<!--            </div>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column prop="status" label="状态" width="120">-->
<!--          <template #default="{row}">-->
<!--            <el-tag :type="statusTagMap[row.status]">-->
<!--              {{ statusMap[row.status] }}-->
<!--            </el-tag>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column label="操作" width="200">-->
<!--          <template #default="{row}">-->
<!--            <el-button-->
<!--                type="primary"-->
<!--                size="small"-->
<!--                @click="editPlan(row)"-->
<!--                icon="Edit"-->
<!--            />-->
<!--            <el-button-->
<!--                type="danger"-->
<!--                size="small"-->
<!--                @click="deletePlan(row.detail_id)"-->
<!--                icon="Delete"-->
<!--            />-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--      </el-table>-->

<!--      <div class="pagination">-->
<!--        <el-pagination-->
<!--            v-model:current-page="currentPage"-->
<!--            :page-size="pageSize"-->
<!--            layout="total, prev, pager, next"-->
<!--            :total="total"-->
<!--            @current-change="handlePageChange"-->
<!--        />-->
<!--      </div>-->
<!--    </el-card>-->

<!--    &lt;!&ndash; 编辑对话框 &ndash;&gt;-->
<!--    <el-dialog-->
<!--        v-model="dialogVisible"-->
<!--        title="编辑行程"-->
<!--        width="40%"-->
<!--    >-->
<!--      <el-form-->
<!--          :model="currentPlan"-->
<!--          label-width="100px"-->
<!--          label-position="top"-->
<!--      >-->
<!--        <el-form-item label="目的地">-->
<!--          <el-input v-model="currentPlan.destination" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="行程天数">-->
<!--          <el-input-number-->
<!--              v-model="currentPlan.duration_days"-->
<!--              :min="1"-->
<!--              :max="30"-->
<!--          />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="预算范围">-->
<!--          <el-input v-model="currentPlan.budget_range" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="行程状态">-->
<!--          <el-select v-model="currentPlan.status">-->
<!--            <el-option-->
<!--                v-for="item in statusOptions"-->
<!--                :key="item.value"-->
<!--                :label="item.label"-->
<!--                :value="item.value"-->
<!--            />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--      </el-form>-->
<!--      <template #footer>-->
<!--        <span class="dialog-footer">-->
<!--          <el-button @click="dialogVisible = false">取消</el-button>-->
<!--          <el-button type="primary" @click="saveEdit">保存</el-button>-->
<!--        </span>-->
<!--      </template>-->
<!--    </el-dialog>-->
<!--  </div>-->
<!--</template>-->

<!--<script setup>-->
<!--import { ref, onMounted } from 'vue'-->
<!--import { ElMessage, ElMessageBox } from 'element-plus'-->
<!--import { Location, Coin, Edit, Delete } from '@element-plus/icons-vue'-->
<!--import axios from 'axios'-->

<!--const plans = ref([])-->
<!--const loading = ref(false)-->
<!--const currentPage = ref(1)-->
<!--const pageSize = 10-->
<!--const total = ref(0)-->
<!--const filterStatus = ref(null)-->
<!--const dialogVisible = ref(false)-->
<!--const currentPlan = ref({})-->

<!--const statusMap = {-->
<!--  1: '待确认',-->
<!--  // 2: '已确认',-->
<!--  // 3: '已完成'-->
<!--}-->

<!--const statusTagMap = {-->
<!--  1: 'warning',-->
<!--  2: 'success',-->
<!--  3: 'info'-->
<!--}-->

<!--const statusOptions = [-->
<!--  { value: " ", label: '全部' },-->
<!--  { value: 1, label: '待确认' },-->
<!--  { value: 2, label: '已确认' },-->
<!--  { value: 3, label: '已完成' }-->
<!--]-->

<!--const fetchPlans = async () => {-->
<!--  try {-->
<!--    loading.value = true-->
<!--    const user = JSON.parse(localStorage.getItem('user'))-->
<!--    console.log('用户信息:', user);-->
<!--    if (!user || !user.user_id) { // 检查用户信息-->
<!--      ElMessage.error('用户信息无效');-->
<!--      return;-->
<!--    }-->
<!--    const res = await axios.get(BASE_URL+`/itinerary-details/user?user_id=${user.user_id}`)-->
<!--    console.log('Request URL:', url); // 打印请求地址-->
<!--    console.log('Response Data:', res.data); // 打印响应数据-->
<!--    plans.value = res.data.data || []-->
<!--    total.value = res.data.total || 0-->
<!--    // loading.value = false;-->
<!--  } catch (error) {-->
<!--    ElMessage.error('获取行程失败')-->
<!--    loading.value = false;-->
<!--  }-->
<!--}-->

<!--const editPlan = (plan) => {-->
<!--  currentPlan.value = { ...plan }-->
<!--  dialogVisible.value = true-->
<!--}-->

<!--const saveEdit = async () => {-->
<!--  try {-->
<!--    await axios.put(BASE_URL+`/itinerary-details/${currentPlan.value.detail_id}`, currentPlan.value)-->
<!--    ElMessage.success('修改成功')-->
<!--    dialogVisible.value = false-->
<!--    fetchPlans()-->
<!--  } catch (error) {-->
<!--    ElMessage.error('修改失败')-->
<!--  }-->
<!--}-->

<!--const deletePlan = async (id) => {-->
<!--  try {-->
<!--    await ElMessageBox.confirm('确定删除该行程？此操作不可恢复！', '警告', {-->
<!--      confirmButtonText: '确认删除',-->
<!--      cancelButtonText: '取消',-->
<!--      type: 'warning'-->
<!--    })-->

<!--    await axios.delete(`/itinerary-details/${id}`)-->
<!--    ElMessage.success('删除成功')-->
<!--    fetchPlans()-->
<!--  } catch (error) {-->
<!--    // 用户取消删除-->
<!--  }-->
<!--}-->

<!--const handlePageChange = (newPage) => {-->
<!--  currentPage.value = newPage-->
<!--  fetchPlans()-->
<!--}-->

<!--onMounted(() => {-->
<!--  fetchPlans()-->
<!--})-->
<!--</script>-->

<!--<style scoped>-->
<!--.my-plan-container {-->
<!--  padding: 20px;-->
<!--  max-width: 1200px;-->
<!--  margin: 0 auto;-->
<!--}-->

<!--.card-header {-->
<!--  display: flex;-->
<!--  justify-content: space-between;-->
<!--  align-items: center;-->
<!--}-->

<!--.plan-overview {-->
<!--  line-height: 1.6;-->

<!--  .destination {-->
<!--    font-weight: 500;-->
<!--    color: var(&#45;&#45;el-color-primary);-->
<!--  }-->

<!--  .budget {-->
<!--    color: #666;-->
<!--    font-size: 0.9em;-->
<!--  }-->
<!--}-->

<!--.filter-select {-->
<!--  width: 150px;-->
<!--}-->

<!--.pagination {-->
<!--  margin-top: 20px;-->
<!--  display: flex;-->
<!--  justify-content: flex-end;-->
<!--}-->

<!--:deep(.el-table__row) {-->
<!--  transition: background-color 0.3s;-->

<!--  &:hover {-->
<!--    background-color: #f5f7fa;-->
<!--  }-->
<!--}-->
<!--</style>-->
